import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'version_state.dart';

/// 版本管理逻辑控制器 - Version Management Logic Controller
/// 处理版本历史的业务逻辑，包括版本对比、回滚、导出等功能
class VersionLogic extends GetxController {
  final VersionState state = VersionState();

  @override
  void onInit() {
    super.onInit();
    _initializeData();
  }

  /// 初始化数据 - Initialize Data
  void _initializeData() {
    loadVersionHistory();
  }



  /// 加载版本历史 - Load Version History
  Future<void> loadVersionHistory() async {
    try {
      state.isLoading = true;
      
      // 模拟加载版本数据 - Simulate loading version data
      await Future.delayed(const Duration(milliseconds: 500));
      
      // 生成模拟版本数据 - Generate mock version data
      final mockVersions = _generateMockVersions();
      state.versions = mockVersions;
      state.filteredVersions = List.from(mockVersions);
      
      // 更新今日版本数量 - Update today's version count
      final today = DateTime.now();
      final todayCount = mockVersions.where((v) => 
        v.createdAt.year == today.year &&
        v.createdAt.month == today.month &&
        v.createdAt.day == today.day
      ).length;
      state.todayVersionCount = todayCount;
      
    } catch (e) {
      Get.snackbar(
        '错误',
        '加载版本历史失败: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    } finally {
      state.isLoading = false;
    }
  }

  /// 生成模拟版本数据 - Generate Mock Version Data
  List<VersionInfo> _generateMockVersions() {
    final now = DateTime.now();
    return [
      VersionInfo(
        id: '1',
        version: '1.5',
        createdAt: now.subtract(const Duration(minutes: 30)),
        contentLength: 1250,
        notes: '优化了提示词的逻辑结构，增加了更多示例',
        contentPreview: '你是一个专业的AI助手，擅长回答各种问题。请根据用户的输入，提供准确、有用的回答...',
        isAutoSave: false,
      ),
      VersionInfo(
        id: '2',
        version: '1.4',
        createdAt: now.subtract(const Duration(hours: 2)),
        contentLength: 1180,
        notes: '修复了格式问题，调整了语言风格',
        contentPreview: '作为AI助手，我需要理解用户的需求并提供帮助。在回答问题时，我会考虑以下几个方面...',
        isAutoSave: true,
      ),
      VersionInfo(
        id: '3',
        version: '1.3',
        createdAt: now.subtract(const Duration(hours: 5)),
        contentLength: 980,
        notes: '添加了新的使用场景和约束条件',
        contentPreview: '请扮演一个知识渊博的专家，能够在多个领域提供专业建议。你的回答应该准确、简洁...',
        isAutoSave: false,
      ),
      VersionInfo(
        id: '4',
        version: '1.2',
        createdAt: now.subtract(const Duration(days: 1)),
        contentLength: 850,
        notes: '初始版本的改进，增加了更多细节',
        contentPreview: '我是一个AI助手，可以帮助用户解决各种问题。我会尽力提供准确和有用的信息...',
        isAutoSave: false,
      ),
      VersionInfo(
        id: '5',
        version: '1.1',
        createdAt: now.subtract(const Duration(days: 2)),
        contentLength: 720,
        notes: '修复了一些表达不清晰的地方',
        contentPreview: '作为AI助手，我的目标是帮助用户获得所需的信息和支持。请告诉我你需要什么帮助...',
        isAutoSave: true,
      ),
      VersionInfo(
        id: '6',
        version: '1.0',
        createdAt: now.subtract(const Duration(days: 3)),
        contentLength: 650,
        notes: '初始版本',
        contentPreview: '你好！我是AI助手，很高兴为你服务。我可以回答问题、提供建议和帮助解决问题...',
        isAutoSave: false,
      ),
    ];
  }

  /// 搜索版本 - Search Versions
  void searchVersions(String query) {
    state.searchQuery = query;
    _filterVersions();
  }

  /// 筛选版本 - Filter Versions
  void _filterVersions() {
    final query = state.searchQuery.toLowerCase();
    if (query.isEmpty) {
      state.filteredVersions = List.from(state.versions);
    } else {
      final filtered = state.versions.where((version) {
        return version.notes.toLowerCase().contains(query) ||
               version.getContentPreview().toLowerCase().contains(query) ||
               version.version.toLowerCase().contains(query);
      }).toList();
      state.filteredVersions = filtered;
    }
    _sortVersions();
  }

  /// 排序版本 - Sort Versions
  void _sortVersions() {
    final sortOrder = state.sortOrder;
    state.filteredVersions.sort((a, b) {
      switch (sortOrder) {
        case 'time_desc':
          return b.createdAt.compareTo(a.createdAt);
        case 'time_asc':
          return a.createdAt.compareTo(b.createdAt);
        case 'version_desc':
          return b.version.compareTo(a.version);
        case 'version_asc':
          return a.version.compareTo(b.version);
        default:
          return b.createdAt.compareTo(a.createdAt);
      }
    });
  }

  /// 切换搜索可见性 - Toggle Search Visibility
  void toggleSearch() {
    state.isSearchVisible = !state.isSearchVisible;
    if (!state.isSearchVisible) {
      state.searchController.clear();
      searchVersions('');
    }
  }

  /// 改变排序方式 - Change Sort Order
  void changeSortOrder(String order) {
    state.sortOrder = order;
    _sortVersions();
    
    String orderText = '';
    switch (order) {
      case 'time_desc':
        orderText = '按时间降序';
        break;
      case 'time_asc':
        orderText = '按时间升序';
        break;
      case 'version_desc':
        orderText = '按版本号降序';
        break;
      case 'version_asc':
        orderText = '按版本号升序';
        break;
    }
    
    Get.snackbar(
      '排序已更改',
      orderText,
      snackPosition: SnackPosition.BOTTOM,
      duration: const Duration(seconds: 1),
    );
  }

  /// 切换版本选择 - Toggle Version Selection
  void toggleVersionSelection(String versionId) {
    if (state.selectedVersions.contains(versionId)) {
      state.selectedVersions.remove(versionId);
    } else {
      // 限制最多选择3个版本进行对比 - Limit to maximum 3 versions for comparison
      if (state.selectedVersions.length >= 3) {
        Get.snackbar(
          '提示',
          '最多只能选择3个版本进行对比',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.orange[100],
          colorText: Colors.orange[800],
        );
        return;
      }
      state.selectedVersions.add(versionId);
    }
  }

  /// 对比选中的版本 - Compare Selected Versions
  void compareSelectedVersions() {
    if (state.selectedVersions.length < 2) {
      Get.snackbar(
        '提示',
        '请至少选择2个版本进行对比',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.orange[100],
        colorText: Colors.orange[800],
      );
      return;
    }

    // 获取选中的版本 - Get selected versions
    final selectedVersions = state.versions
        .where((v) => state.selectedVersions.contains(v.id))
        .toList();

    // 按版本号排序 - Sort by version number
    selectedVersions.sort((a, b) => b.version.compareTo(a.version));

    // 显示对比对话框 - Show comparison dialog
    _showComparisonDialog(selectedVersions);
  }

  /// 显示版本对比对话框 - Show Version Comparison Dialog
  void _showComparisonDialog(List<VersionInfo> versions) {
    Get.dialog(
      Dialog(
        child: Container(
          width: Get.width * 0.9,
          height: Get.height * 0.8,
          padding: const EdgeInsets.all(20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 对话框标题 - Dialog Title
              Row(
                children: [
                  const Icon(Icons.compare_arrows, color: Colors.blue),
                  const SizedBox(width: 8),
                  const Text(
                    '版本对比',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const Spacer(),
                  IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: () => Get.back(),
                  ),
                ],
              ),
              
              const Divider(),
              
              // 版本信息 - Version Information
              SizedBox(
                height: 60,
                child: ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: versions.length,
                  itemBuilder: (context, index) {
                    final version = versions[index];
                    return Container(
                      margin: const EdgeInsets.only(right: 12),
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Colors.blue[50],
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: Colors.blue[200]!),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            'v${version.version}',
                            style: const TextStyle(
                              fontWeight: FontWeight.w600,
                              color: Colors.blue,
                            ),
                          ),
                          Text(
                            formatDateTime(version.createdAt),
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey[600],
                            ),
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),
              
              const SizedBox(height: 16),
              
              // 对比内容 - Comparison Content
              Expanded(
                child: SingleChildScrollView(
                  child: Column(
                    children: versions.map((version) {
                      return Container(
                        margin: const EdgeInsets.only(bottom: 16),
                        padding: const EdgeInsets.all(16),
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.grey[300]!),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Row(
                              children: [
                                Text(
                                  'v${version.version}',
                                  style: const TextStyle(
                                    fontWeight: FontWeight.w600,
                                    fontSize: 16,
                                  ),
                                ),
                                const SizedBox(width: 8),
                                Text(
                                  '(${version.getContentLength()} 字符)',
                                  style: TextStyle(
                                    color: Colors.grey[600],
                                    fontSize: 12,
                                  ),
                                ),
                              ],
                            ),
                            if (version.notes.isNotEmpty) ...[
                              const SizedBox(height: 8),
                              Text(
                                '备注: ${version.notes}',
                                style: TextStyle(
                                  color: Colors.grey[700],
                                  fontSize: 14,
                                ),
                              ),
                            ],
                            const SizedBox(height: 12),
                            Text(
                              version.getContentPreview(),
                              style: const TextStyle(
                                fontSize: 14,
                                height: 1.5,
                              ),
                            ),
                          ],
                        ),
                      );
                    }).toList(),
                  ),
                ),
              ),
              
              // 操作按钮 - Action Buttons
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () => Get.back(),
                    child: const Text('关闭'),
                  ),
                  const SizedBox(width: 8),
                  ElevatedButton(
                    onPressed: () {
                      Get.back();
                      _exportComparisonResult(versions);
                    },
                    child: const Text('导出对比结果'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 查看版本详情 - View Version Detail
  void viewVersionDetail(String versionId) {
    final version = state.versions.firstWhere((v) => v.id == versionId);
    
    Get.dialog(
      Dialog(
        child: Container(
          width: Get.width * 0.8,
          height: Get.height * 0.7,
          padding: const EdgeInsets.all(20),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题 - Title
              Row(
                children: [
                  const Icon(Icons.info_outline, color: Colors.blue),
                  const SizedBox(width: 8),
                  Text(
                    '版本详情 - v${version.version}',
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.w600,
                    ),
                  ),
                  const Spacer(),
                  IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: () => Get.back(),
                  ),
                ],
              ),
              
              const Divider(),
              
              // 版本信息 - Version Information
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.grey[50],
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        const Text('创建时间: ', style: TextStyle(fontWeight: FontWeight.w500)),
                        Text(formatDateTime(version.createdAt)),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        const Text('内容长度: ', style: TextStyle(fontWeight: FontWeight.w500)),
                        Text('${version.getContentLength()} 字符'),
                      ],
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        const Text('保存类型: ', style: TextStyle(fontWeight: FontWeight.w500)),
                        Text(version.isAutoSave ? '自动保存' : '手动保存'),
                      ],
                    ),
                    if (version.notes.isNotEmpty) ...[
                      const SizedBox(height: 8),
                      const Text('备注: ', style: TextStyle(fontWeight: FontWeight.w500)),
                      const SizedBox(height: 4),
                      Text(version.notes),
                    ],
                  ],
                ),
              ),
              
              const SizedBox(height: 16),
              
              // 内容预览 - Content Preview
              const Text(
                '内容预览:',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.w600,
                ),
              ),
              const SizedBox(height: 8),
              
              Expanded(
                child: Container(
                  padding: const EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey[300]!),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: SingleChildScrollView(
                    child: Text(
                      version.getContentPreview(),
                      style: const TextStyle(
                        fontSize: 14,
                        height: 1.5,
                      ),
                    ),
                  ),
                ),
              ),
              
              // 操作按钮 - Action Buttons
              const SizedBox(height: 16),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [
                  TextButton(
                    onPressed: () => Get.back(),
                    child: const Text('关闭'),
                  ),
                  const SizedBox(width: 8),
                  ElevatedButton(
                    onPressed: () {
                      Get.back();
                      restoreVersion(versionId);
                    },
                    child: const Text('恢复此版本'),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 恢复版本 - Restore Version
  void restoreVersion(String versionId) {
    Get.dialog(
      AlertDialog(
        title: const Text('确认恢复'),
        content: const Text('确定要恢复到此版本吗？当前未保存的更改将会丢失。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Get.back();
              _performRestore(versionId);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.orange,
            ),
            child: const Text('确认恢复'),
          ),
        ],
      ),
    );
  }

  /// 执行恢复操作 - Perform Restore Operation
  void _performRestore(String versionId) {
    try {
      // 模拟恢复操作 - Simulate restore operation
      final version = state.versions.firstWhere((v) => v.id == versionId);
      
      Get.snackbar(
        '恢复成功',
        '已恢复到版本 v${version.version}',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[800],
      );
      
      // 清除选择 - Clear selection
      state.selectedVersions.clear();
      
      // 返回编辑页面 - Return to edit page
      Get.back();
      
    } catch (e) {
      Get.snackbar(
        '恢复失败',
        '恢复版本时发生错误: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 导出版本 - Export Version
  void exportVersion(String versionId) {
    _showExportDialog([versionId]);
  }

  /// 导出所有版本 - Export All Versions
  void exportAllVersions() {
    final allVersionIds = state.versions.map((v) => v.id).toList();
    _showExportDialog(allVersionIds);
  }

  /// 显示导出对话框 - Show Export Dialog
  void _showExportDialog(List<String> versionIds) {
    String selectedFormat = 'json';
    
    Get.dialog(
      AlertDialog(
        title: const Text('导出版本'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('将导出 ${versionIds.length} 个版本'),
            const SizedBox(height: 16),
            const Text('选择导出格式:'),
            const SizedBox(height: 8),
            DropdownButtonFormField<String>(
              value: selectedFormat,
              decoration: const InputDecoration(
                border: OutlineInputBorder(),
                contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
              ),
              items: const [
                DropdownMenuItem(value: 'json', child: Text('JSON 格式')),
                DropdownMenuItem(value: 'txt', child: Text('文本格式')),
                DropdownMenuItem(value: 'md', child: Text('Markdown 格式')),
              ],
              onChanged: (value) {
                if (value != null) selectedFormat = value;
              },
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Get.back();
              _performExport(versionIds, selectedFormat);
            },
            child: const Text('导出'),
          ),
        ],
      ),
    );
  }

  /// 执行导出操作 - Perform Export Operation
  void _performExport(List<String> versionIds, String format) {
    try {
      // 模拟导出操作 - Simulate export operation
      Get.snackbar(
        '导出成功',
        '已导出 ${versionIds.length} 个版本为 $format 格式',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[800],
      );
    } catch (e) {
      Get.snackbar(
        '导出失败',
        '导出版本时发生错误: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 导出对比结果 - Export Comparison Result
  void _exportComparisonResult(List<VersionInfo> versions) {
    try {
      // 模拟导出对比结果 - Simulate export comparison result
      Get.snackbar(
        '导出成功',
        '已导出 ${versions.length} 个版本的对比结果',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[800],
      );
    } catch (e) {
      Get.snackbar(
        '导出失败',
        '导出对比结果时发生错误: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 删除版本 - Delete Version
  void deleteVersion(String versionId) {
    final version = state.versions.firstWhere((v) => v.id == versionId);
    
    Get.dialog(
      AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除版本 v${version.version} 吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Get.back();
              _performDelete(versionId);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 执行删除操作 - Perform Delete Operation
  void _performDelete(String versionId) {
    try {
      state.versions.removeWhere((v) => v.id == versionId);
      state.filteredVersions.removeWhere((v) => v.id == versionId);
      state.selectedVersions.remove(versionId);
      
      Get.snackbar(
        '删除成功',
        '版本已删除',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[800],
      );
    } catch (e) {
      Get.snackbar(
        '删除失败',
        '删除版本时发生错误: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 复制版本 - Duplicate Version
  void duplicateVersion(String versionId) {
    try {
      final originalVersion = state.versions.firstWhere((v) => v.id == versionId);
      
      // 创建新版本 - Create new version
      final newVersion = VersionInfo(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        version: '${originalVersion.version}-copy',
        createdAt: DateTime.now(),
        contentLength: originalVersion.getContentLength(),
        notes: '复制自版本 v${originalVersion.version}',
        contentPreview: originalVersion.getContentPreview(),
        isAutoSave: false,
      );
      
      state.versions.insert(0, newVersion);
      state.filteredVersions.insert(0, newVersion);
      
      Get.snackbar(
        '复制成功',
        '已创建版本副本',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[800],
      );
    } catch (e) {
      Get.snackbar(
        '复制失败',
        '复制版本时发生错误: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 清理旧版本 - Clear Old Versions
  void clearOldVersions() {
    Get.dialog(
      AlertDialog(
        title: const Text('清理旧版本'),
        content: const Text('将删除30天前的自动保存版本，手动保存的版本不会被删除。确定继续吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Get.back();
              _performClearOldVersions();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.orange,
            ),
            child: const Text('确认清理'),
          ),
        ],
      ),
    );
  }

  /// 执行清理旧版本操作 - Perform Clear Old Versions Operation
  void _performClearOldVersions() {
    try {
      final thirtyDaysAgo = DateTime.now().subtract(const Duration(days: 30));
      final versionsToRemove = state.versions.where((v) => 
        v.isAutoSave && v.createdAt.isBefore(thirtyDaysAgo)
      ).toList();
      
      for (final version in versionsToRemove) {
        state.versions.removeWhere((v) => v.id == version.id);
        state.filteredVersions.removeWhere((v) => v.id == version.id);
        state.selectedVersions.remove(version.id);
      }
      
      Get.snackbar(
        '清理完成',
        '已清理 ${versionsToRemove.length} 个旧版本',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[800],
      );
    } catch (e) {
      Get.snackbar(
        '清理失败',
        '清理旧版本时发生错误: $e',
        snackPosition: SnackPosition.BOTTOM,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 格式化日期时间 - Format DateTime
  String formatDateTime(DateTime dateTime) {
    final now = DateTime.now();
    final difference = now.difference(dateTime);
    
    if (difference.inMinutes < 1) {
      return '刚刚';
    } else if (difference.inMinutes < 60) {
      return '${difference.inMinutes}分钟前';
    } else if (difference.inHours < 24) {
      return '${difference.inHours}小时前';
    } else if (difference.inDays < 7) {
      return '${difference.inDays}天前';
    } else {
      return '${dateTime.year}-${dateTime.month.toString().padLeft(2, '0')}-${dateTime.day.toString().padLeft(2, '0')} ${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}';
    }
  }
}